package contactbook.test.mock.entitymanager;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.FlushModeType;
import javax.persistence.Query;
import javax.persistence.TemporalType;

import org.hibernate.Transaction;
import org.hibernate.classic.Session;

public class QueryMock implements Query {
	
	String query;
	Map<String, Object> parameters;
	
	public QueryMock(String arg) {
		this.query = arg;
		parameters = new HashMap<String, Object>();
	}
	
	@Override
	public Query setParameter(String arg0, Object arg1) {
		parameters.put(arg0, arg1);
		return this;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List getResultList() {
		Transaction tx = null;
		Session session = SessionFactoryUtil.getInstance().getCurrentSession();
		List l = null;
		
		tx = session.beginTransaction();
		org.hibernate.Query q = session.createQuery(query);
		for (String key : parameters.keySet()) {
			q.setParameter(key, parameters.get(key));
		}
		l = q.list();
		tx.commit();
		
		return l;
	}

	@Override
	public Object getSingleResult() {
		Transaction tx = null;
		Session session = SessionFactoryUtil.getInstance().getCurrentSession();
		Object obj = null;
		
		tx = session.beginTransaction();
		org.hibernate.Query q = session.createQuery(query);
		for (String key : parameters.keySet()) {
			q.setParameter(key, parameters.get(key));
		}
		obj = q.uniqueResult();
		tx.commit();
		
		return obj;
	}
	
	@Override
	public int executeUpdate() {
		return 0;
	}

	@Override
	public Query setFirstResult(int arg0) {
		return this;
	}

	@Override
	public Query setFlushMode(FlushModeType arg0) {
		return this;
	}

	@Override
	public Query setHint(String arg0, Object arg1) {
		return this;
	}

	@Override
	public Query setMaxResults(int arg0) {
		return this;
	}

	@Override
	public Query setParameter(int arg0, Object arg1) {
		return this;
	}

	@Override
	public Query setParameter(String arg0, Date arg1, TemporalType arg2) {
		return this;
	}

	@Override
	public Query setParameter(String arg0, Calendar arg1, TemporalType arg2) {
		return this;
	}

	@Override
	public Query setParameter(int arg0, Date arg1, TemporalType arg2) {
		return this;
	}

	@Override
	public Query setParameter(int arg0, Calendar arg1, TemporalType arg2) {
		return this;
	}

}
